import React, { useCallback, useRef, useState } from 'react';
import {
  Button,
  Card,
  Col,
  Form,
  Icon,
  Input,
  Menu,
  message,
  Modal,
  Popconfirm,
  Row,
  Table,
} from 'antd';
import { useAntdTable, useBoolean } from 'ahooks';
import FlexibleLayout, { Content, Sider } from '@/layouts/FlexibleLayout';
import { GlobalFormLayout } from '@/layouts/Form';
import Space from '@/components/Space';
import request from '@/utils/request';
import IconLink from '@/components/IconLink';
import { EditableCell, EditableContext } from './context';
import useModal from '@/hooks/UseModal';
import CreateEndpointModal from './components/CreateEndpointModal';

function getTableData({ current, pageSize, _endpointName, endpointCode, scene }) {
  return request.post('/serverEndpoint/page', {
    data: {
      current,
      pageSize,
      endpointName: _endpointName,
      endpointCode,
      scene,
    },
  });
}

export const HTTP_CALL_REQUEST_URL_SCENE = 'HTTP_CALL_REQUEST_URL';

function ServerEndpointManager({ form }) {
  const { getFieldDecorator, resetFields, getFieldsValue, validateFields } = form;
  const scene = HTTP_CALL_REQUEST_URL_SCENE;
  const [refreshFlag, { toggle }] = useBoolean(false);
  const [mask, setMask] = useState(false);
  const { visible, showModal, hideModal } = useModal();
  const [refreshLoading, setRefreshLoading] = useState(false);

  const {
    tableProps: { pagination, dataSource, loading, ...restTableProps },
  } = useAntdTable(
    query => {
      return getTableData({ ...query, ...getFieldsValue(), scene });
    },
    {
      defaultPageSize: 10,
      refreshDeps: [refreshFlag],
    }
  );

  const refresh = useCallback(() => {
    toggle();
  }, [toggle]);

  const reloadScene = () => {
    setRefreshLoading(true);
    request
      .post(`/serverEndpoint/reloadScene?scene=${scene}`)
      .then(() => {
        message.success('刷新成功');
      })
      .finally(() => {
        setRefreshLoading(false);
      });
  };

  const [editingKey, setEditingKey] = useState();

  const isEditing = record => record.endpointId === editingKey;
  const cancelEditing = () => setEditingKey(undefined);

  const handleSaveRow = (form, endpointId) => {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      setMask(true);
      request
        .post('/serverEndpoint/update', {
          data: {
            endpointId,
            endpointUrl: row.endpointUrl,
            endpointName: row.endpointName,
          },
        })
        .then(() => {
          message.success('修改成功');
          cancelEditing();
          refresh();
        })
        .finally(() => {
          setMask(false);
        });
    });
  };

  const handleDeleteRow = endpointId => {
    setMask(true);
    request
      .post(`/serverEndpoint/delete?endpointId=${endpointId}`)
      .then(() => {
        message.success('删除成功');
        refresh();
      })
      .finally(() => {
        setMask(false);
      });
  };

  const columns = [
    {
      title: '端点名称',
      dataIndex: 'endpointName',
      onCell: record => ({
        record,
        dataIndex: 'endpointName',
        title: '端点名称',
        editing: isEditing(record),
        handleSaveRow,
      }),
    },
    // {
    //   title: '端点编码',
    //   dataIndex: 'endpointCode',
    // },
    {
      title: '端点URL',
      dataIndex: 'endpointUrl',
      width: '750px',
      onCell: record => ({
        record,
        dataIndex: 'endpointUrl',
        title: '端点URL',
        editing: isEditing(record),
        handleSaveRow,
        copyable: true,
      }),
    },
    {
      title: '操作',
      width: '150px',
      render: (_text, record) => {
        return (
          <Space divider="vertical">
            {isEditing(record) ? (
              <EditableContext.Consumer>
                {form => (
                  <IconLink icon="save" onClick={() => handleSaveRow(form, record.endpointId)}>
                    保存
                  </IconLink>
                )}
              </EditableContext.Consumer>
            ) : (
              <IconLink icon="edit" onClick={() => setEditingKey(record.endpointId)}>
                编辑
              </IconLink>
            )}
            <Popconfirm
              title="确定要删除该条记录吗"
              onConfirm={() => handleDeleteRow(record.endpointId)}
            >
              <IconLink icon="delete" className="text-danger">
                删除
              </IconLink>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  return (
    <>
      <FlexibleLayout>
        <Sider>
          {({ height }) => (
            <Card title="应用场景" className="cute" style={{ height }} bodyStyle={{ padding: 16 }}>
              <Menu style={{ border: 'none' }} defaultSelectedKeys={[scene]}>
                <Menu.Item key="HTTP_CALL_REQUEST_URL">HTTP调用_请求地址</Menu.Item>
              </Menu>
            </Card>
          )}
        </Sider>
        <Content>
          {({ height }) => (
            <Card
              title="端点列表"
              className="cute"
              style={{ height }}
              bodyStyle={{ padding: 16 }}
              extra={
                <Button type="primary" icon="plus" onClick={showModal}>
                  添加端点
                </Button>
              }
            >
              <Form {...GlobalFormLayout} className="margin-bottom">
                <Row gutter={16}>
                  <Col span={6}>
                    <Form.Item label="端点名称">
                      {getFieldDecorator('_endpointName')(
                        <Input onPressEnter={refresh} placeholder="请输入" />
                      )}
                    </Form.Item>
                  </Col>
                  <Col span={6}>
                    <Form.Item label="端点编码">
                      {getFieldDecorator('endpointCode')(
                        <Input onPressEnter={refresh} placeholder="请输入" />
                      )}
                    </Form.Item>
                  </Col>
                  <Col span={6}>
                    <Space>
                      <Button type="primary" onClick={refresh}>
                        查询
                      </Button>
                      <Button type="default" onClick={() => resetFields()}>
                        重置
                      </Button>
                      <Button type="primary" onClick={reloadScene} loading={refreshLoading}>
                        刷新缓存
                      </Button>
                    </Space>
                  </Col>
                </Row>
              </Form>
              <EditableContext.Provider value={form}>
                <Table
                  loading={loading || mask}
                  rowKey="endpointId"
                  components={{ body: { cell: EditableCell } }}
                  bordered
                  columns={columns}
                  dataSource={dataSource}
                  pagination={{ ...pagination, onChange: cancelEditing }}
                  {...restTableProps}
                />
              </EditableContext.Provider>
            </Card>
          )}
        </Content>
      </FlexibleLayout>
      <CreateEndpointModal visible={visible} onCancel={hideModal} onOk={refresh} scene={scene} />
    </>
  );
}

export default Form.create()(ServerEndpointManager);
